<template>
	<view class="container">
		<!-- 搜索栏 -->
		<uv-sticky :offset-top="0" z-index="99">
			<view class="search">
				<view class="search-input">
					<view class="search-model">
						<uv-input v-model="modelStr" placeholder="请输入型号" shape="square" border="surround"
							:clearable="true" fontSize="13"></uv-input>
					</view>
					<view class="search-brand">
						<uv-input v-model="brandStr" placeholder="请输入品牌" shape="square" border="surround"
							:clearable="true" fontSize="13"></uv-input>
					</view>
				</view>
				<view class="search-btn" @click="search">搜索</view>
			</view>

			<!-- 排序 -->
			<view class="sort">
				<uv-drop-down ref="dropDown" sign="dropDown_1" text-size="26rpx" text-active-size="30rpx"
					text-active-color="#000000" :extra-icon="{name:'arrow-down-fill',color:'#666',size:'24rpx'}"
					:extra-active-icon="{name:'arrow-up-fill',color:'#000000',size:'24rpx'}"
					:defaultValue="defaultValue" :custom-style="{padding: '6rpx 20rpx'}">
					<uv-drop-down-item name="brand" type="1" :label="brandLabel" :value="dropItem('brand').value"
						@click="openBrandPopup()"></uv-drop-down-item>
						
					<uv-drop-down-item name="brand" type="1" :label="authLabel" :value="dropItem('auth').value"
						@click="openAuthPopup()"></uv-drop-down-item>
						
					<uv-drop-down-item name="price" type="2" :label="dropItem('price').label"
						:value="dropItem('price').value" @click="setActive('price')">
					</uv-drop-down-item>
					<!-- <uv-drop-down-item name="star" type="2" :label="dropItem('star').label"
						:value="dropItem('star').value" @click="setActive('star')">
					</uv-drop-down-item> -->
				</uv-drop-down>
				<uv-popup ref="brandPopupRef" mode="top" closeable="true">
					<scroll-view scroll-y="true" style="max-height: 80vh;">
						<view class="slot-content">
							<view class="item-box">
								<view class="item" :class="[item.active ? 'active' : '']"
									@tap="brandTagClick(index, item.id, item.name)" v-for="(item, index) in brandList"
									:key="item.id">
									{{item.name}}
								</view>
							</view>
						</view>
					</scroll-view>
				</uv-popup>
				
				<uv-popup ref="authPopupRef" mode="top" closeable="true">
					<scroll-view scroll-y="true" style="max-height: 80vh;">
						<view class="slot-content">
							<view class="item-box">
								<view class="item" :class="[item.active ? 'active' : '']"
									@tap="authTagClick(index, item.id, item.name)" v-for="(item, index) in authList"
									:key="item.id">
									{{item.name}}
								</view>
							</view>
						</view>
					</scroll-view>
				</uv-popup>
				
				<uv-picker ref="areaPicker" keyName="name" :columns="[areaList]" @confirm="areaConfirm"></uv-picker>
				<uv-drop-down-popup sign="dropDown_1" :click-overlay-on-close="true" :currentDropItem="currentDropItem"
					@clickItem="clickItem"></uv-drop-down-popup>
			</view>
		</uv-sticky>


		<!-- 骨架屏 -->
		<uv-skeletons :loading="loading" :skeleton="skeleton" :animate="animate"></uv-skeletons>

		<!-- 产品 -->
		<view class="product" v-for="(item, index) in goodsList" :key="item.id">
			<view class="product-info" @tap="onGoods(item.id)">
				<view class="product-image">
					<uv-image :src="$wanlshop.appurl(item.image)" width="240rpx" height="240rpx" radius="5px"
						:lazyLoad="true" :observeLazyLoad="true"></uv-image>
					<image v-if="item.is_hot" :src="$wanlshop.appurl('/assets/img/fire.png')" class="hot-badge"></image>
				</view>
				<view class="product-right">
					<view class="product-right-name">
						<uv-tags :text="item.tag.text" size="mini" type="warning" :color="item.tag.text_color"
							:bgColor="item.tag.bg_color" :borderColor="item.tag.bg_color"></uv-tags>
						<uv-text :text="item.title" :bold="true" color="#000000" size="32rpx" lines="1"
							customStyle="padding-left: 10rpx;"></uv-text>
					</view>
					<view class="product-right-item">
						<view class="item-left">品牌：{{item.brand.name}}</view>
						<view>产地：{{item.origin}}</view>
					</view>
					<view class="product-right-item">
						<view class="item-left">发货地：{{item.area.name}}</view>
						<view>库存：{{item.stock}}</view>
					</view>
					<view style="display: flex; align-items: center;">
						星级：
						<view style="padding-left: 0rpx;">
							<uv-rate v-model="item.star" activeColor="#fe5400" size="14" readonly></uv-rate>
						</view>
					</view>
					<view class="price">
						<view class="price-box">
							<view class="novip">
								<image class="novip-icon" src="/static/images/default/novip.png"></image>
								<text class="novip-price" v-if="verify_status == 'success'">￥{{item.price}}</text>
								<text class="novip-price" v-else>???</text>
							</view>
							<view class="vip">
								<image class="vip-icon" src="/static/images/default/vip.png"></image>
								<text class="vip-price" v-if="verify_status == 'success'">￥{{item.vip_price}}</text>
								<text class="vip-price" v-else @tap="onAuth()">认证后查看</text>
							</view>
						</view>
						<view class="addcart-icon">
							<image @click.stop="addCart(item)" src="/static/images/default/addcart.png"></image>
						</view>
					</view>
				</view>
			</view>
		</view>

		<liu-drag-button @clickBtn="toGuider">购物指南</liu-drag-button>
	</view>
</template>

<script>
	export default {
		computed: {
			dropItem() {
				return (name) => {
					const resultItem = this.result.find(item => item.name === name);
					if (resultItem) {
						return {
							label: resultItem.label,
							value: resultItem.value
						};
					}
					return this[name] ? {
						label: this[name].label,
						value: this[name].value
					} : {
						label: '',
						value: ''
					};
				}
			},
			currentDropItem() {
				return this[this.activeName] || {};
			}
		},
		data() {
			return {
				reload: false, //判断是否上拉
				total: 0, //数据量
				current_page: 1, //当前页码
				last_page: 1, //总页码
				status: 'loading',
				contentText: {
					contentdown: ' ',
					contentrefresh: '加载中',
					contentnomore: ''
				},

				// 骨架屏
				loading: true,
				animate: true,
				skeleton: [{
					type: 'flex',
					num: 5,
					children: [{
						type: 'custom',
						num: 1,
						style: 'width:240rpx;height:240rpx;marginRight: 30rpx;borderRadius: 10rpx; marginTop: 30rpx; marginLeft: 30rpx;'
					}, {
						type: 'line',
						num: 5,
						style: [
							'width:420rpx; marginTop: 30rpx; marginRight: 30rpx;',
							'width:400rpx;',
							'width:240rpx;',
							'width:360rpx;',
							'width:200rpx;'
						]
					}]
				}],

				brandLabel: '品牌',
				authLabel:'类别',
				searchModelStr: '',
				modelStr: "",
				brandStr: "",
				defaultValue: ["brand", "auth", "price"],
				result: [{
					name: 'price',
					label: '价格排序',
					value: 'price'
				}],
				activeName: '',
				brand: {
					label: '品牌',
					value: 'brand',
					activeIndex: 0,
					color: '#333',
					activeColor: '#fe5400'
				},
				auth: {
					label: '类别',
					value: 'auth',
					activeIndex: 0,
					color: '#333',
					activeColor: '#fe5400'
				},
				price: {
					label: '综合排序',
					value: 'price',
					activeIndex: 0,
					color: '#333',
					activeColor: '#fe5400',
					child: [{
						label: '综合排序',
						value: 'price all'
					}, {
						label: '价格升序',
						value: 'price asc'
					}, {
						label: '价格降序',
						value: 'price desc'
					}]
				},
				star: {
					label: '星级排序',
					value: 'star',
					activeIndex: 0,
					color: '#333',
					activeColor: '#fe5400',
					child: [{
						label: '全部',
						value: 'star all'
					}, {
						label: '五星',
						value: 'star5'
					}, {
						label: '四星',
						value: 'star4'
					}, {
						label: '三星',
						value: 'star3'
					}, {
						label: '二星',
						value: 'star2'
					}, {
						label: '一星',
						value: 'star1'
					}]
				},
				brandId: '', // 品牌ID
				brandList: [], // 品牌数据
				authList: [
					{
						id: 0,
						name: '全部',
						active: true
					},
					{
						id: 1,
						name: '授权',
						active: false
					},
					{
						id: 2,
						name: '其他品牌授权',
						active: false
					}
				],
				areaId: '', // 地区ID
				areaList: [], // 地区数据
				goodsList: [],
				sortStr: "",
				starStr: "",
				verify_status: this.$store.state.user ? this.$store.state.user.verify_status : 'no_auth',
			}
		},
		onLoad(options) {
			
			console.log(options,'options');
			// 赋值给verify_status
			this.verify_status = this.$store.state.user ? this.$store.state.user.verify_status : 'no_auth';

			this.loadData();
			this.brandListApi();
		},
		onPullDownRefresh() {
			this.current_page = 1;
			this.reload = true;
			this.loadData();
			this.brandListApi();
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onReachBottom() {
			//判断是否最后一页
			if (this.current_page >= this.last_page) {
				this.status = 'noMore';
			} else {
				this.reload = false;
				this.current_page = this.current_page + 1; //页码+1
				this.status = 'loading';
				this.loadData();
			}
		},
		methods: {
			onAuth() {
				uni.navigateTo({
					url: '/pages/company/auth'
				})
			},
			async refreshData() {
			  await uni.request({
				url: '/wanlshop/user/refresh',
				method: 'POST',
				success: res => {
				  this.$store.commit('statistics/edit', res.data.statistics);
				  this.$store.commit('user/setUserInfo', res.data.userinfo);
				}
			  });
			},
			// 设置当前选中的值
			setActive(name) {
				this.activeName = name;
			},
			clickItem(e) {
				// 下面有重新赋值，所以用let
				let {
					label,
					value
				} = e;
				const findIndex = this.result.findIndex(item => item.name == this.activeName);
				if (this.defaultValue.indexOf(value) > -1 && this[this.activeName].label) {
					label = this[this.activeName].label;
				}
				// 已经存在筛选项
				if (findIndex > -1) {
					this.$set(this.result, findIndex, {
						name: this.activeName,
						label,
						value
					})
				} else {
					this.result.push({
						name: this.activeName,
						label,
						value
					});
				}
				this.result = this.result.filter(item => this.defaultValue.indexOf(item.value) == -1);

				// this.result.forEach(item => {
				this.current_page = 1;
				this.reload = true;

				let itemValue = e.value;

				if (itemValue.includes("price")) {
					// 价格排序
					if (itemValue == 'price all') {
						itemValue = '';
					}
					this.sortStr = itemValue;
					this.loadData();
				} else if (itemValue.includes("star")) {
					// 星级筛选
					if (itemValue == 'star all') {
						itemValue = '';
					}
					this.starStr = itemValue;
					this.loadData();
				}
				// })
			},

			// 开启品牌选择
			openBrandPopup() {
				this.$refs.brandPopupRef.open();
			},
			
			openAuthPopup() {
				this.$refs.authPopupRef.open();
			},

			// 选择品牌
			brandTagClick(index, id, name) {
				// 重置所有选项
				this.brandList.forEach(item => item.active = false);

				// 激活当前选中的品牌
				this.brandList[index].active = true;
				this.brandId = id;
				this.brandLabel = name;
				this.current_page = 1;
				this.reload = true;
				this.loadData();
				this.$refs.brandPopupRef.close();
			},
			
			// 选择类别
			authTagClick(index, id, name) {
				// 重置所有选项
				this.authList.forEach(item => item.active = false);
			
				// 激活当前选中的品牌
				this.authList[index].active = true;
				this.authId = id;
				this.authLabel = name;
				this.current_page = 1;
				this.reload = true;
				this.loadData();
				this.$refs.authPopupRef.close();
			},

			// 搜索
			search() {
				let text = this.modelStr;
				if(text.includes('百润分享')) {
					let newText = text.replace('百润分享','')
					let id = parseInt(newText);
					this.$wanlshop.to(`/pages/share/share?share_goods_id=${id}`, 'fade-in', 100);
				} else {
					this.current_page = 1;
					this.reload = true;
					this.loadData();

					// 更换品牌列表
					this.brandListApi();
				}
			},

			// 加入购物车
			addCart(item) {
				if (item.sku.stock == 0) {
					this.$wanlshop.msg('商品库存不足', 1500, true, 'error');
					return;
				}
				this.$store.dispatch('companyAuth/verify').then((result) => {
					if (!result) {
						return;
					}
					this.$store.dispatch('cart/add', {
						shop_id: item.shop_id,
						shop_name: item.shop.shopname,
						goods_id: item.id,
						title: item.title,
						number: 1,
						image: item.image,
						sku: item.sku,
						sku_id: item.sku.id,
						sum: item.price,
						brand_name: item.brand.name,
						model: item.model,
					});
					this.$wanlshop.msg('已加购物车', 1500, false, 'success');
				});
			},

			//跳转购物指南
			toGuider() {
				this.$wanlshop.to('/pages/guider/guider');
			},

			async loadData(type) {
				this.status = 'loading';
				this.loading = true;
				
				this.refreshData();

				// 判断上拉还是下拉
				if (type === 'upper') {
					this.current_page = 1;
				} else if (type === 'lower') {
					if (this.current_page >= this.last_page) {
						this.status = 'noMore';
						return false;
					} else {
						this.current_page += 1;
					}
				}
				// uni.showLoading({
				// 	title: "加载中..."
				// })
				
				// 请求数据
				await uni.request({
					url: '/wanlshop.product/lists',
					data: {
						page: this.current_page,
						model: this.modelStr,
						brand_name: this.brandStr,
						brand_id_list: this.brandId,
						area_id: this.areaId,
						sort_str: this.sortStr,
						star: this.starStr,
						auth_type: this.authId ?? 0
					},
					success: res => {
						uni.hideLoading();
						this.loading = false;
						// let user = uni.getStorageSync('wanlshop:user');
						// console.log(this.$store.state.user,'vuexStore')
						// if (user && user.verify_status == 'success') {
						this.goodsList = this.reload ? res.data.list.data : this.goodsList.concat(res
								.data.list.data);
						
						
						// } else {
						// 	const processedData = res.data.list.data.map(item => ({
						// 		...item,
						// 		price: '???',
						// 		vip_price: '认证后查看'
						// 	}));
						// 	this.goodsList = this.reload ? processedData : this.goodsList.concat(
						// 		processedData);
						// }

						this.current_page = res.data.list.current_page; //当前页码
						this.last_page = res.data.list.last_page; //总页码
						if (res.data.list.total === 0) {
							uni.showToast({
								icon: "none",
								title: "暂无数据"
							})
						}
						
						if (this.current_page === 1) {
							uni.pageScrollTo({
							  scrollTop: 0,
							  duration: 30
							});
						}
						
						// 判断是否还有数据
						if (res.data.list.current_page === res.data.list.last_page || res.data.list
							.total === 0) {
							this.status = 'noMore';
						} else {
							this.status = 'more';
						}
						
						
					},
					fail: (err) => {
						// uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: "失败: " + err.errMsg
						});
					}
				});
			},

			// 获取品牌
			async brandListApi() {
				uni.showLoading({
					title: "加载中..."
				})

				let data = {};
				if (this.modelStr.length > 0) {
					data.model = this.modelStr
				}
				if (this.brandStr.length > 0) {
					data.brand_name = this.brandStr
				}
				// 请求数据
				await uni.request({
					url: '/wanlshop.product/brandList',
					data: data,
					success: res => {
						uni.hideLoading();
						this.brandList = res.data;
					}
				});
			},
		},
		onShow() {
			this.refreshData()
		},
		watch: {
			"$store.state.user.verify_status": function(newValue) {
				this.verify_status = newValue;
			}
		},
	}
</script>

<style>
	page {
		background: #FFFFFF;
	}

	.uv-scroll-list {
		padding: 0 !important;
	}

	.uv-input {
		background: #FFFFFF !important;
		height: 66rpx !important;
		padding: 2rpx 2rpx 2rpx 6rpx !important;
	}

	.uv-tags__text {
		font-size: 22rpx !important;
	}
</style>

<style lang="scss" scoped>
	.container {
		.head {
			background: #fe5400;
			background: -webkit-linear-gradient(0deg, #fe5400 0%, #fe5400 100%);
			background: linear-gradient(0deg, #fe5400 0%, #fe5400 100%);
			height: 100rpx;
		}

		.search {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 30rpx 30rpx 30rpx;
			background: #fe5400;

			.search-input {
				display: flex;
				align-items: center;
				justify-content: space-between;
				width: 90%;

				.search-model {
					width: 60%;
					margin-right: 20rpx;
				}

				.search-brand {
					width: 40%;
				}
			}

			.search-btn {
				font-size: 26rpx;
				color: #FFFFFF;
			}
		}
	}

	.product {
		margin: 6rpx 30rpx 0rpx;
		padding: 14rpx 0rpx;
		border-bottom: 1rpx solid #e5e5e5;

		.product-image {
			position: relative;
			
			.hot-badge {
				position: absolute;
				top: 0;
				right: 0;
				width: 40rpx;
				height: 40rpx;
				z-index: 1;
			}
		}

		.product-info {
			display: flex;
			align-items: center;
			justify-content: space-around;

			.product-right {
				width: 100%;
				font-size: 26rpx;
				color: #949494;
				line-height: 48rpx;
				margin-left: 30rpx;

				.product-right-name {
					display: flex;
					align-items: center;
				}

				.product-right-item {
					display: flex;
					align-items: center;

					.item-left {
						min-width: 50%;
					}
				}

				.price {
					padding-top: 6rpx;
					font-weight: 600;
					display: flex;
					align-items: center;
					justify-content: space-between;
					width: 100%;

					.price-box {
						display: flex;
						align-items: center;

						.novip {
							display: flex;
							align-items: center;

							.novip-icon {
								width: 36rpx;
								height: 36rpx;
							}

							.novip-price {
								color: #000000;
								font-size: 32rpx;
							}
						}

						.vip {
							display: flex;
							align-items: center;
							padding-left: 20rpx;

							.vip-icon {
								width: 36rpx;
								height: 36rpx;
							}

							.vip-price {
								color: #FE6300;
								font-size: 28rpx;
							}
						}
					}

					.addcart-icon {
						display: flex;
						align-items: center;

						image {
							width: 36rpx;
							height: 36rpx;
						}
					}
				}
			}
		}
	}

	.slot-content {
		background-color: #FFFFFF;
		padding: 80rpx 20rpx 20rpx 20rpx;

		.item-box {
			margin-bottom: 50rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-wrap: wrap;

			.item {
				background-color: #F8F8F8;
				color: #000000;
				padding: 14rpx 0rpx;
				border-radius: 100rpx;
				margin: 0rpx 10rpx 30rpx 10rpx;
				width: 30%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 26rpx;
			}

			.active {
				color: #FFFFFF;
				background-color: #fe5400;
			}
		}
	}

	.guider {
		position: fixed;
		right: 74rpx;
		bottom: 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;

		image {
			width: 60rpx;
			height: 60rpx;
		}

		text {
			font-size: 22rpx;
		}
	}

	.brand-list {
		background-color: #FFFFFF;
		margin: 20rpx;

		.brand-items {
			display: flex;

			.brand-item {
				background-color: #F8F8F8;
				color: #000000;
				min-width: 120rpx;
				border-radius: 20rpx;
				margin: 10rpx 18rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.active {
				color: #FFFFFF;
				background-color: #fe5400;
			}
		}
	}
</style>